package main

import (
	"net"
	"log"
	"fmt"
	"reflect"
	"io"
	"bufio"
	"os"
)

func main() {
	Get2()
}

func Get4() {
	conn := request()
	io.Copy(os.Stdout, conn)
	conn.Close()
}

func Get3() {
	conn := request()

	r := bufio.NewReader(conn)
	for{
		line, err := r.ReadString('\n')
		if err==io.EOF{
			conn.Close()
		}
		fmt.Print(line)
	}
}

func Get2(){
	conn := request()
	buf := make([]byte, 10)
	var (
		n int
		err error
	)
	//todo how the loop break
	for{
		n,err = conn.Read(buf)
		if err == io.EOF{
			conn.Close()
		}
		fmt.Print(string(buf[:n]))
	}

	fmt.Println(string(buf[:n]))
}

func Get1() {
	conn := request()

	buf := make([]byte, 1024)

	n,err := conn.Read(buf) //接收到的内容大小。
	if err!=nil && err!=io.EOF{//io.EOF在网络编程中表示对端把链接关闭了。
		log.Fatal(err)
	}
	fmt.Println(string(buf[:n]))
	conn.Close()
}


func request() net.Conn{
	conn,err := net.Dial("tcp", "www.baidu.com:80")
	if err!=nil{
		log.Fatal(err)
	}
	fmt.Println("Remote IP address is: ", conn.RemoteAddr().String())
	fmt.Println("Local IP address is: ", conn.LocalAddr().String())
	fmt.Println("“conn.LocalAddr()”所对应的数据类型是：",reflect.TypeOf(conn.LocalAddr()))
	fmt.Println("“conn.RemoteAddr().String()”所对应的数据类型是：",reflect.TypeOf(conn.RemoteAddr().String()))

	n,err := conn.Write([]byte("GET / HTTP/1.1\r\n\r\n"))
	if err!=nil{
		log.Fatal(err)
	}
	fmt.Println("the size sent to server is:", n)

	return conn
}